package cmd

import (
	"fmt"
	"os"

	"gitee.com/miajio/fyleos/pro/app/file"
	"gitee.com/miajio/fyleos/pro/cache"
	fyle "gitee.com/miajio/go-base-util/pkg/file"
	"gitee.com/miajio/go-base-util/pkg/ginx"
	"github.com/spf13/cobra"
)

var rootCmd = &cobra.Command{
	Use:   "fyleos",
	Short: "file os",
	Long:  "file os",
}

var runCmd = &cobra.Command{
	Use:   "run",
	Short: "file os run",
	Long:  "file os run",
	Run: func(cmd *cobra.Command, args []string) {
		fmt.Printf("openPath %s port %d", cache.OpenPath, cache.Port)
		_, err := fyle.New(cache.OpenPath)
		if err != nil {
			if err := os.MkdirAll(cache.OpenPath, os.ModePerm); err != nil {
				cache.Log.Errorf("open path fail: %v", err)
				return
			}
		}
		cache.RootFile, _ = fyle.New(cache.OpenPath)

		x := ginx.GinDefault()
		x.AddRouter(file.FileRouter)
		x.Run(fmt.Sprintf(":%d", cache.Port))
	},
}

func init() {
	runCmd.Flags().IntVarP(&cache.Port, "port", "p", 8080, "fyleOS web server port")
	runCmd.Flags().StringVarP(&cache.OpenPath, "openPath", "o", "./root", "open path")
	rootCmd.AddCommand(runCmd)
}

func Execute() error {
	return rootCmd.Execute()
}
